package org.springblade.tms.module.sap.base;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.http.Method;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.PropertyNamingStrategy;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.mpobjects.bdparsii.eval.Expression;
import com.mpobjects.bdparsii.eval.Parser;
import com.mpobjects.bdparsii.eval.Scope;
import com.mpobjects.bdparsii.eval.Variable;
import com.mpobjects.bdparsii.tokenizer.ParseException;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springblade.common.utils.EnumUtils;
import org.springblade.core.mp.base.BaseEntity;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.utils.BeanUtil;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.system.feign.IDictBizClient;
import org.springblade.tms.global.constant.DictCodeConstant;
import org.springblade.tms.global.enums.*;
import org.springblade.tms.global.exception.CommonException;
import org.springblade.tms.global.utils.HttpUtils;
import org.springblade.tms.module.car.entity.TMCar;
import org.springblade.tms.module.currencytype.entity.TMCurrencyType;
import org.springblade.tms.module.currencytype.service.ICurrencyTypeService;
import org.springblade.tms.module.historicalquotation.entity.TMHistoricalQuotation;
import org.springblade.tms.module.historicalquotation.service.IHistoricalQuotationService;
import org.springblade.tms.module.inquirycarrier.entity.TMInquiryCarrier;
import org.springblade.tms.module.inquirycarrier.service.IInquiryCarrierService;
import org.springblade.tms.module.inquirysheet.entity.TMInquirySheet;
import org.springblade.tms.module.inquirysheet.service.IInquirySheetService;
import org.springblade.tms.module.offer.entity.TMOffer;
import org.springblade.tms.module.offer.service.IOfferService;
import org.springblade.tms.module.sap.dto.*;
import org.springblade.tms.module.supercargoinfo.entity.TMSupercargoInfo;
import org.springblade.tms.module.userinfo.entity.TMUserInfo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static org.springblade.common.constant.TenantConstant.DEFAULT_TENANT_ID;
import static org.springblade.tms.global.enums.SapMsgStatusEnum.S;
import static org.springblade.tms.global.enums.UserTypeEnum.CARRIER;

/**
 * @author: wzq
 * @className: SapRequestService
 * @createDate: 2022/3/8
 * @description: 请求SAP接口
 */
@Service
@GlobalTransactional
@AllArgsConstructor
@Slf4j
public class SapRequestService {

    private final IDictBizClient dictClient;
    private final IInquirySheetService iInquirySheetService;
    private final IInquiryCarrierService iInquiryCarrierService;
    private final IHistoricalQuotationService historicalQuotationService;
    private final IOfferService offerService;
    private final ICurrencyTypeService currencyTypeService;

    /***
     * wzq
     * 推送需求单补全信息至TM,分配运单推送至TM
     * @param info
     */
    public SapTransportRespDTO pushTmForDemandExtraInfo(SapTransportOrderDTO info) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        SapTransportDTO sapTransportDTO = BeanUtil.copy(info, SapTransportDTO.class);
        assert sapTransportDTO != null;
        sapTransportDTO.getDetail().add(info);
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.WAYBILL_SYNCHRONIZATION_SAP_INTERFACE, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(new SapDataDTO(Collections.singletonList(sapTransportDTO)), config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);

        SapDataVO sapDataVO = JSONUtil.toBean(response, SapDataVO.class);
        SapTransportRespDTO sapTransportRespDTO = JSONUtil.toBean(JSON.toJSONString(sapDataVO.getData()), SapTransportRespDTO.class);
        log.info(response);

        if (!S.value().equals(sapTransportRespDTO.getId())) {
            if (Strings.isNotBlank(sapTransportRespDTO.getText())) {
                CommonException.throwCommonException(sapTransportRespDTO.getText());
            } else {
                CommonException.throwCommonException("返回参数为空");
            }
        }
        return sapTransportRespDTO;
    }

    /**
     * @param info:
     * @return void
     * @author yr
     * @description 推送需求单运单事件到TM
     * @date 2022/3/28 10:57
     */
    public void pushTmForUpdateWaybill(WaybillEventDTO info) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        if (Strings.isNotBlank(info.getExceptionPic())) {
            String[] split = info.getExceptionPic().split(";");
            ArrayList<String> list = ListUtil.toList(split);
            list.forEach(s -> s = picURL(s));
            String exceptionPic = StringUtil.join(list, ";");
            info.setExceptionPic(exceptionPic);
        }
        info.setSignPic(picURL(info.getSignPic()));
        info.setOverPic(picURL(info.getOverPic()));
        List<WaybillEventDTO> waybillEventDTOS = Collections.singletonList(info);
        SapWaybillEventDTO sapWaybillEventDTO = SapWaybillEventDTO.builder().build();
        sapWaybillEventDTO.setType(info.getType());
        sapWaybillEventDTO.setItem(waybillEventDTOS);
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.WAYBILL_UPDATE, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(new SapDataDTO(Collections.singletonList(sapWaybillEventDTO)), config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        if(!response.equals("\"\"")){
			SapDataVO sapDataVO = JSONUtil.toBean(response, SapDataVO.class);
			SapFreightStatementData sapData = BeanUtil.copy(sapDataVO.getData(), SapFreightStatementData.class);
			if (!S.value().equals(sapData.getId())) {
				if (Strings.isNotBlank(sapData.getText())) {
					CommonException.throwCommonException(sapData.getText());
				} else {
					CommonException.throwCommonException("sap返回数据未空");
				}
			}
		}
    }

    /**
     * @param userInfoList:
     * @return R
     * @author yr
     * @description 司机承运商主数据
     * @date 2022/3/15 10:08
     */
    public R driverMasterData(List<TMUserInfo> userInfoList, String action) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String userType = userInfoList.get(0).getUserType();
        //司机主数据
        if (userType.equals(UserTypeEnum.CHAUFFEUR.getValue())) {
            DriverDto driverDto = new DriverDto();
            driverDto.setType(SapDateType.DRIVER.value());
            driverDto.setAction(action);
            for (TMUserInfo tmUserInfo : userInfoList) {
                DriverDtoItem driverDtoItem = BeanUtil.copy(tmUserInfo, DriverDtoItem.class);
                if (driverDtoItem != null) {
                    driverDtoItem.setCertificateWorkPic(picURL(driverDtoItem.getCertificateWorkPic()));
                    driverDtoItem.setCertificateDriverPicBack(picURL(driverDtoItem.getCertificateDriverPicBack()));
                    driverDtoItem.setCertificateDriverPicFront(picURL(driverDtoItem.getCertificateDriverPicFront()));
                    driverDtoItem.setIdCardPicBack(picURL(driverDtoItem.getIdCardPicBack()));
                    driverDtoItem.setIdCardPicFront(picURL(driverDtoItem.getIdCardPicFront()));
                    driverDtoItem.setIdCardNo(driverDtoItem.getCertificateDriverNo());
                }
                driverDto.getItem().add(driverDtoItem);
            }
            String jsonStr = JSON.toJSONString(new SapDataDTO(Collections.singletonList(driverDto)), config);
            pushTM(jsonStr);
            //承运商主数据
        } else if (userType.equals(CARRIER.getValue())) {
            CarrierDto carrierDto = new CarrierDto();
            for (TMUserInfo tmUserInfo : userInfoList) {
                CarrierDtoItem carrierDtoItem = BeanUtil.copy(tmUserInfo, CarrierDtoItem.class);
                if (carrierDtoItem != null) {
                    carrierDtoItem.setCertificateOperationPic(picURL(carrierDtoItem.getCertificateOperationPic()));
                    carrierDtoItem.setCertificateTransportPic(picURL(carrierDtoItem.getCertificateTransportPic()));
                    carrierDtoItem.setLegalPersonPicBack(picURL(carrierDtoItem.getLegalPersonPicBack()));
                    carrierDtoItem.setLegalPersonPicFront(picURL(carrierDtoItem.getLegalPersonPicFront()));
                }
                carrierDto.setAction(action);
                carrierDto.setType(SapDateType.CARRIER.value());
                carrierDto.getItem().add(carrierDtoItem);
            }
            String jsonStr = JSON.toJSONString(new SapDataDTO(Collections.singletonList(carrierDto)), config);
            pushTM(jsonStr);
        }
        return R.status(true);
    }


    /**
     * @param supercargoInfoList:
     * @return R
     * @author yr
     * @description 押运员主数据
     * @date 2022/3/15 10:08
     */
    public R escortMasterData(List<TMSupercargoInfo> supercargoInfoList, String action) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        SupercargoDto supercargoDto = new SupercargoDto();
        for (TMSupercargoInfo supercargoInfo : supercargoInfoList) {
            SupercargoDtoItem supercargoDtoItem = BeanUtil.copy(supercargoInfo, SupercargoDtoItem.class);
            if (supercargoDtoItem != null) {
                supercargoDtoItem.setCertificateWorkPic(picURL(supercargoDtoItem.getCertificateWorkPic()));
                supercargoDtoItem.setIdCardPicBack(picURL(supercargoDtoItem.getIdCardPicBack()));
                supercargoDtoItem.setIdCardPicFront(picURL(supercargoDtoItem.getIdCardPicFront()));
            }
            supercargoDto.setAction(action);
            supercargoDto.setType(SapDateType.SUPERCARGO.value());
            supercargoDto.getItem().add(supercargoDtoItem);
        }
        String jsonStr = JSON.toJSONString(new SapDataDTO(Collections.singletonList(supercargoDto)), config);
        pushTM(jsonStr);
        return R.status(true);
    }

    /**
     * @param carList:
     * @return R
     * @author yr
     * @description 车辆主数据
     * @date 2022/3/15 10:08
     */
    public R vehicleMasterData(List<TMCar> carList, String action) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        CarDto carDto = new CarDto();
        for (TMCar car : carList) {
            CarDtoItem carDtoItem = BeanUtil.copy(car, CarDtoItem.class);
            carDto.setAction(action);
            if (carDtoItem != null) {
                carDtoItem.setCarType(EnumUtils.getEnumByValue(CarType.class, carDtoItem.getCarType()).get().getDescription());
                carDtoItem.setTransportGoodsType(EnumUtils.getEnumByValue(CargoTypeEnum.class, carDtoItem.getTransportGoodsType()).get().getDescription());
                carDtoItem.setEnableGps(EnumUtils.getEnumByValue(WhetherEnum.class, car.getEnableGps().toString()).get().getDescription());
                carDtoItem.setEsv(EnumUtils.getEnumByValue(WhetherEnum.class, car.getEsv().toString()).get().getDescription());
                carDtoItem.setFireOff(EnumUtils.getEnumByValue(WhetherEnum.class, car.getFireOff().toString()).get().getDescription());
                if (!carDtoItem.getCarTransportPic().isEmpty()) {
                    carDtoItem.setCarTransportPic(picURL(carDtoItem.getCarTransportPic()));
                }
                if (!carDtoItem.getCarWorkPic().isEmpty()) {
                    carDtoItem.setCarWorkPic(picURL(carDtoItem.getCarWorkPic()));

                }
                if (!carDtoItem.getContainerReportPic().isEmpty()) {
                    carDtoItem.setContainerReportPic(picURL(carDtoItem.getContainerReportPic()));
                }
                if (!carDtoItem.getBindCarTransportPic().isEmpty()) {
                    carDtoItem.setBindCarTransportPic(picURL(carDtoItem.getBindCarTransportPic()));
                }
                if (!carDtoItem.getBindCarWorkPic().isEmpty()) {
                    carDtoItem.setBindCarWorkPic(picURL(carDtoItem.getBindCarWorkPic()));
                }
            }
            carDto.setType(SapDateType.CAR.value());
            carDto.getItem().add(carDtoItem);
        }
        String jsonStr = JSON.toJSONString(new SapDataDTO(Collections.singletonList(carDto)), config);
        pushTM(jsonStr);
        return R.status(true);
    }

    //基础数据上报TM
    private void pushTM(String json) {
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.BASIC_DATA, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = json;
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        SapDataVO sapDataVO = JSONUtil.toBean(response, SapDataVO.class);
        SapData sapData = BeanUtil.copy(sapDataVO.getData(), SapData.class);
        if (!S.value().equals(sapData.getId())) {
            if (Strings.isNotBlank(sapData.getText())) {
                CommonException.throwCommonException(sapData.getText());
            } else {
                CommonException.throwCommonException("sap返回数据为空");
            }
        }
    }

    /**
     * @param :
     * @return String：结算单号
     * @author yr
     * @description 运费结算单
     * @date 2022/3/30 14:29
     */
    public List<SapFreightStatementDataItem> freightStatement(List<SapFreightStatementDTO> sapFreightStatementDTO) {
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.FREIGHT_SETTLEMENT_DOCUMENT, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(new SapDataVO(sapFreightStatementDTO), config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new HashMap<>(), null, null, body, url);
        log.info(response);
        SapFreightStatementData sapData = JSON.parseObject(response, SapFreightStatementData.class);
        if (!S.value().equals(sapData.getId())) {
            if (sapData == null) {
                CommonException.throwCommonException("接口返回值异常");
            } else {
                CommonException.throwCommonException(sapData.getText());
            }
        }
        sapData.getDetail().forEach(sapFreightStatementDataItem -> {
            if (sapFreightStatementDataItem.getSfirId() == null) {
                sapFreightStatementDataItem.setSfirId("");
            }
        });
        return sapData.getDetail();
    }

    //图片url拼接
    private String picURL(String url) {
        if (Strings.isNotBlank(url)) {
            return dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.URL, DEFAULT_TENANT_ID).getData() + url;
        } else {
            return url;
        }
    }

    /**
     * @param sapExceptionCostDTO:
     * @return void
     * @author yr
     * @description 异常费用上报
     * @date 2022/4/24 14:45
     */
    public void abnormalExpenses(SapExceptionCostDTO sapExceptionCostDTO) {
        SerializeConfig config = new SerializeConfig();
        sapExceptionCostDTO.getSapExceptionCostDTOItems()
                .forEach(sapExceptionCostDTOItem -> sapExceptionCostDTOItem.setFile(picURL(sapExceptionCostDTOItem.getFile())));
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.ABNORMAL_EXPENSES, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(new SapDataDTO(Collections.singletonList(sapExceptionCostDTO)), config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        SapDataVO sapDataVO = JSONUtil.toBean(response, SapDataVO.class);
        SapFreightStatementData sapData = BeanUtil.copy(sapDataVO.getData(), SapFreightStatementData.class);
        if (!S.value().equals(sapData.getId())) {
            if (Strings.isNotBlank(sapData.getText())) {
                CommonException.throwCommonException(sapData.getText());

            } else {
                CommonException.throwCommonException("sap返回数据异常");

            }
        }
    }

    /**
     * @param sapBillingDTOS:
     * @return void
     * @author yr
     * @description 发票上报
     * @date 2022/4/26 9:31
     */
    public void submitAnInvoice(List<SapBillingDTO> sapBillingDTOS) {
        String account = AuthUtil.getUser().getAccount();
        sapBillingDTOS.forEach(sapBillingDTO -> {
            sapBillingDTO.setZfptp(picURL(sapBillingDTO.getZfptp()));
            sapBillingDTO.setZsl((sapBillingDTO.getZsl().divide(BigDecimal.valueOf(100), 2, BigDecimal.ROUND_HALF_UP)));
            sapBillingDTO.setPrice(sapBillingDTO.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP));
            sapBillingDTO.setTotal(sapBillingDTO.getTotal().setScale(2, BigDecimal.ROUND_HALF_UP));
            sapBillingDTO.setCREPERSON(account);
        });
        SerializeConfig config = new SerializeConfig();
        config.propertyNamingStrategy = PropertyNamingStrategy.SnakeCase;
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.INVOICE_INFORMATION, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        String body = JSON.toJSONString(new SapBillingItemData(sapBillingDTOS), config);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        SapDataVO sapDataVO = JSONUtil.toBean(response, SapDataVO.class);
        SapFreightStatementData sapData = BeanUtil.copy(sapDataVO.getData(), SapFreightStatementData.class);
        if (!S.value().equals(sapData.getId())) {
            if (Strings.isNotBlank(sapData.getText())) {
                CommonException.throwCommonException(sapData.getText());

            } else {
                CommonException.throwCommonException("sap返回数据异常");

            }
        }
    }

    /**
     * @param : 询价单id
     * @return void
     * @author yr
     * @description 报价上报sap
     * @date 2022/5/25 10:42
     */
    public void quotedPrice(Long inquiryId) {
        TMInquirySheet tmInquirySheet = iInquirySheetService.getById(inquiryId);
        SAPQuotationSubmissionDTO sapQuotationSubmissionDTO = new SAPQuotationSubmissionDTO();
        sapQuotationSubmissionDTO.setREQUEST_ID(tmInquirySheet.getRequestId());
        sapQuotationSubmissionDTO.setUSERID("0");
        sapQuotationSubmissionDTO.setTYPE("submit");
        sapQuotationSubmissionDTO.setCREATEID("1");
        sapQuotationSubmissionDTO.setREQUESTNAME(tmInquirySheet.getTitle());
        sapQuotationSubmissionDTO.setISNEXTFLOW("1");
        sapQuotationSubmissionDTO.setCREATETIME(LocalDateTime.now());
        sapQuotationSubmissionDTO.setREMARK("");
        String domesticTrade = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.DOMESTIC_TRADE, DEFAULT_TENANT_ID).getData();
        String bulkCargo = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.BULK_CARGO, DEFAULT_TENANT_ID).getData();
        String foreignTrade = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.FOREIGN_TRADE, DEFAULT_TENANT_ID).getData();
        if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.domesticTrade.getValue())) {
            sapQuotationSubmissionDTO.setWORKFLOWID(domesticTrade);
        } else if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.bulkCargo.getValue())) {
            sapQuotationSubmissionDTO.setWORKFLOWID(bulkCargo);
        } else if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.foreignTrade.getValue())) {
            sapQuotationSubmissionDTO.setWORKFLOWID(foreignTrade);
        }
        sapQuotationSubmissionDTO.setItem(new ArrayList<>());
        if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.domesticTrade.getValue())) {
            //内贸报价上报数据封装
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery().eq(TMInquiryCarrier::getParentId, tmInquirySheet.getId()).list();
            List<Long> inquiryCarrierIds = tmInquiryCarriers.stream().map(TMInquiryCarrier::getId).collect(Collectors.toList());
            List<TMOffer> tmOffers = offerService.lambdaQuery().in(TMOffer::getParentId, inquiryCarrierIds).list();
            Map<Long, List<TMOffer>> offerByParentIdMap = tmOffers.stream().collect(Collectors.groupingBy(TMOffer::getParentId));
            List<TMHistoricalQuotation> tmHistoricalQuotations = historicalQuotationService.lambdaQuery()
                    .in(TMHistoricalQuotation::getParentId, inquiryCarrierIds)
                    .ne(TMHistoricalQuotation::getBidder, UserTypeEnum.ADMIN.getDescription())
                    .list();
            Map<Long, List<TMHistoricalQuotation>> historicalQuotationMap = tmHistoricalQuotations.stream().collect(Collectors.groupingBy(TMHistoricalQuotation::getParentId));
            tmInquiryCarriers.forEach(tmInquiryCarrier -> {
                List<TMOffer> offers = offerByParentIdMap.get(tmInquiryCarrier.getId());
                InquiryPriceVo inquiryPriceVo = new InquiryPriceVo();
                inquiryPriceVo.setCarrierId(tmInquiryCarrier.getCarrierId());
                inquiryPriceVo.setCarrierName(tmInquiryCarrier.getCarrierName());
                //如果没有报价
                if (offers == null) {
                    SAPQuotationSubmissionDTO.Item item = SAPQuotationSubmissionDTO.Item.builder()
                            .CYS(tmInquiryCarrier.getCarrierName())
                            .LIFNR(tmInquiryCarrier.getCarrierId())
                            .build();
                    sapQuotationSubmissionDTO.getItem().add(item);
                    return;
                }
                HashMap<String, Object> hashMap = new HashMap<>();
                for (TMOffer offer : offers) {
                    hashMap.put(offer.getFieldName(), offer.getValue());
                }
                BeanUtil.copy(hashMap, inquiryPriceVo);
                String inquiryPriceJson = JSON.toJSONString(inquiryPriceVo);
                SAPQuotationSubmissionDTO.Item item = JSONUtil.toBean(inquiryPriceJson, SAPQuotationSubmissionDTO.Item.class);
                if (tmInquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.FINISH.value())) {
                    item.setZBJG("是");
                } else {
                    item.setZBJG("否");
                }
                sapQuotationSubmissionDTO.getItem().add(item);
                List<TMHistoricalQuotation> historicalQuotations = historicalQuotationMap.get(tmInquiryCarrier.getId());
                if (historicalQuotations == null) {
                    return;
                } else if (historicalQuotations.size() == 1) {
                    TMHistoricalQuotation tmHistoricalQuotation = historicalQuotations.get(0);
                    InquiryPriceVo priceVo = JSONUtil.toBean(tmHistoricalQuotation.getQuotation(), InquiryPriceVo.class);
                    item.setLSBJ1(priceVo.getQuotedPrice());
                } else {
                    List<TMHistoricalQuotation> historicalQuotationList = historicalQuotations.stream()
                            .sorted(Comparator.comparing(BaseEntity::getCreateTime)).collect(Collectors.toList());

                    TMHistoricalQuotation tmHistoricalQuotation1 = historicalQuotationList.get(0);
                    InquiryPriceVo priceVo1 = JSONUtil.toBean(tmHistoricalQuotation1.getQuotation(), InquiryPriceVo.class);
                    item.setLSBJ1(priceVo1.getQuotedPrice());

                    TMHistoricalQuotation tmHistoricalQuotation2 = historicalQuotationList.get(1);
                    InquiryPriceVo priceVo2 = JSONUtil.toBean(tmHistoricalQuotation2.getQuotation(), InquiryPriceVo.class);
                    item.setLSBJ2(priceVo2.getQuotedPrice());
                }
            });
            //排序
            List<SAPQuotationSubmissionDTO.Item> quoted = new ArrayList<>();
            List<SAPQuotationSubmissionDTO.Item> notQuoted = new ArrayList<>();
            sapQuotationSubmissionDTO.getItem().forEach(sapQuotationSubmission -> {
                if (sapQuotationSubmission.getZZBJ() == null || sapQuotationSubmission.getZZBJ().equals("")) {
                    notQuoted.add(sapQuotationSubmission);
                } else {
                    quoted.add(sapQuotationSubmission);
                }
            });
            List<SAPQuotationSubmissionDTO.Item> items = quoted.stream()
                    .sorted(Comparator.comparing(SAPQuotationSubmissionDTO.Item::getZZBJ)).collect(Collectors.toList());
            items.addAll(notQuoted);
            sapQuotationSubmissionDTO.setItem(items);
        } else if (tmInquirySheet.getWorkflowId().equals(EnquiryTypeEnum.bulkCargo.getValue())) {
            //散货报价上报数据封装
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery().eq(TMInquiryCarrier::getParentId, tmInquirySheet.getId()).list();
            List<Long> inquiryCarrierIds = tmInquiryCarriers.stream().map(TMInquiryCarrier::getId).collect(Collectors.toList());
            List<TMOffer> tmOffers = offerService.lambdaQuery().in(TMOffer::getParentId, inquiryCarrierIds).list();
            Map<Long, List<TMOffer>> offerByParentIdMap = tmOffers.stream().collect(Collectors.groupingBy(TMOffer::getParentId));
            tmInquiryCarriers.forEach(tmInquiryCarrier -> {
                List<TMOffer> offers = offerByParentIdMap.get(tmInquiryCarrier.getId());
                InquiryPriceVo inquiryPriceVo = new InquiryPriceVo();
                inquiryPriceVo.setCarrierId(tmInquiryCarrier.getCarrierId());
                inquiryPriceVo.setCarrierName(tmInquiryCarrier.getCarrierName());
                //如果没有报价
                if (offers == null) {
                    SAPQuotationSubmissionDTO.Item item = SAPQuotationSubmissionDTO.Item.builder()
                            .CYS(tmInquiryCarrier.getCarrierName())
                            .LIFNR(tmInquiryCarrier.getCarrierId())
                            .TOTAL("")
                            .build();
                    sapQuotationSubmissionDTO.getItem().add(item);
                    return;
                }
                HashMap<String, Object> hashMap = new HashMap<>();
                for (TMOffer offer : offers) {
                    hashMap.put(offer.getFieldName(), offer.getValue());
                }
                BeanUtil.copy(hashMap, inquiryPriceVo);
                String inquiryPriceJson = JSON.toJSONString(inquiryPriceVo);
                SAPQuotationSubmissionDTO.Item item = JSONUtil.toBean(inquiryPriceJson, SAPQuotationSubmissionDTO.Item.class);
                if (tmInquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.FINISH.value())) {
                    item.setZBJG("是");
                } else {
                    item.setZBJG("否");
                }
                sapQuotationSubmissionDTO.getItem().add(item);

            });
            List<SAPQuotationSubmissionDTO.Item> quoted = new ArrayList<>();
            List<SAPQuotationSubmissionDTO.Item> notQuoted = new ArrayList<>();
            sapQuotationSubmissionDTO.getItem().forEach(sapQuotationSubmission -> {
                if (sapQuotationSubmission.getZZBJ_SH1() == null || sapQuotationSubmission.getZZBJ_SH1().equals("")) {
                    notQuoted.add(sapQuotationSubmission);
                } else {
                    quoted.add(sapQuotationSubmission);
                }
            });
            List<SAPQuotationSubmissionDTO.Item> items = quoted.stream()
                    .sorted(Comparator.comparing(SAPQuotationSubmissionDTO.Item::getZZBJ_SH1)).collect(Collectors.toList());
            items.addAll(notQuoted);
            sapQuotationSubmissionDTO.setItem(items);
        } else {
            //外贸报价上报数据封装
            //取报价部分
            List<TMInquiryCarrier> tmInquiryCarriers = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquirySheet.getId())
                    .isNotNull(TMInquiryCarrier::getShippingCompany)
                    .list();
            //取未报价部分
            List<TMInquiryCarrier> InquiryCarrierList = iInquiryCarrierService.lambdaQuery()
                    .eq(TMInquiryCarrier::getParentId, tmInquirySheet.getId())
                    .list();
            Map<String, List<TMInquiryCarrier>> collect = InquiryCarrierList.stream().collect(Collectors.groupingBy(TMInquiryCarrier::getCarrierId));
            collect.forEach((s, inquiryCarriers) -> {
                if (inquiryCarriers.size() == 1) {
                    tmInquiryCarriers.addAll(inquiryCarriers);
                }
            });
            List<Long> inquiryCarrierIds = tmInquiryCarriers.stream().map(TMInquiryCarrier::getId).collect(Collectors.toList());
            List<TMOffer> tmOffers = offerService.lambdaQuery().in(TMOffer::getParentId, inquiryCarrierIds).list();
            Map<Long, List<TMOffer>> offerByParentIdMap = tmOffers.stream().collect(Collectors.groupingBy(TMOffer::getParentId));
            tmInquiryCarriers.forEach(tmInquiryCarrier -> {
                List<TMOffer> offers = offerByParentIdMap.get(tmInquiryCarrier.getId());
                InquiryPriceVo inquiryPriceVo = new InquiryPriceVo();
                inquiryPriceVo.setCarrierId(tmInquiryCarrier.getCarrierId());
                inquiryPriceVo.setCarrierName(tmInquiryCarrier.getCarrierName());
                //如果没有报价
                if (offers == null) {
                    SAPQuotationSubmissionDTO.Item item = SAPQuotationSubmissionDTO.Item.builder()
                            .CYS(tmInquiryCarrier.getCarrierName())
                            .LIFNR(tmInquiryCarrier.getCarrierId())
                            .TOTAL("")
                            .build();
                    sapQuotationSubmissionDTO.getItem().add(item);
                    return;
                }
                HashMap<String, Object> hashMap = new HashMap<>();
                for (TMOffer offer : offers) {
                    hashMap.put(offer.getFieldName(), offer.getValue());
                }
                BeanUtil.copy(hashMap, inquiryPriceVo);
                String inquiryPriceJson = JSON.toJSONString(inquiryPriceVo);
                SAPQuotationSubmissionDTO.Item item = JSONUtil.toBean(inquiryPriceJson, SAPQuotationSubmissionDTO.Item.class);
                if (tmInquiryCarrier.getQuotationStatus().equals(EnquiryStatusEnum.FINISH.value())) {
                    item.setZBJG("是");
                } else {
                    item.setZBJG("否");
                }
                if (Objects.nonNull(tmInquiryCarrier.getWinningBoxQuantity())) {
                    item.setZBXL(tmInquiryCarrier.getWinningBoxQuantity().toPlainString());
                }
                //外贸排名所需数据
                TMCurrencyType currencyType = currencyTypeService.lambdaQuery().eq(TMCurrencyType::getName, "USD").one();
                BigDecimal typeRate = currencyType.getRate();
                Scope scope = new Scope();
                Variable rate = scope.getVariable("rate");
                Expression expr = null;
                try {
                    expr = Parser.parse("shippingFee * rate + portCharges", scope);
                } catch (ParseException e) {
                    CommonException.throwCommonException("合计计算公式格式错误");
                }
                rate.setValue(typeRate);
                if (offers != null) {
                    Variable shippingFee = scope.getVariable("shippingFee");
                    shippingFee.setValue(BigDecimal.valueOf(Long.parseLong(item.getHYF())));
                    Variable portCharges = scope.getVariable("portCharges");
                    portCharges.setValue(BigDecimal.valueOf(Long.parseLong(item.getYZF())));
                    BigDecimal total = expr.evaluate();
                    item.setTOTAL(total.toPlainString());
                }
                sapQuotationSubmissionDTO.getItem().add(item);
            });
            List<SAPQuotationSubmissionDTO.Item> quoted = new ArrayList<>();
            List<SAPQuotationSubmissionDTO.Item> notQuoted = new ArrayList<>();
            sapQuotationSubmissionDTO.getItem().forEach(sapQuotationSubmission -> {
                if (sapQuotationSubmission.getTOTAL() == null || sapQuotationSubmission.getTOTAL().equals("")) {
                    notQuoted.add(sapQuotationSubmission);
                } else {
                    quoted.add(sapQuotationSubmission);
                }
            });
            List<SAPQuotationSubmissionDTO.Item> items = quoted.stream()
                    .sorted(Comparator.comparing(SAPQuotationSubmissionDTO.Item::getTOTAL)).collect(Collectors.toList());
            items.addAll(notQuoted);
            sapQuotationSubmissionDTO.setItem(items);
        }
        //封装数据
        SAPQuotationSubmissionVO sapQuotationSubmissionVO = BeanUtil.copy(sapQuotationSubmissionDTO, SAPQuotationSubmissionVO.class);
        sapQuotationSubmissionVO.setITEM(new ArrayList<>());
        sapQuotationSubmissionDTO.getItem().forEach(item -> {
            ArrayList<SAPQuotationSubmissionVO.Item.ItemItem> itemItems = new ArrayList<>();
            Map<String, Object> map = BeanUtil.toMap(item);
            map.forEach((s, o) -> {
                if (o != null && !o.equals("")) {
                    SAPQuotationSubmissionVO.Item.ItemItem itemItem = SAPQuotationSubmissionVO.Item.ItemItem
                            .builder()
                            .FIELDNAME(s)
                            .FIELDVALUE((String) o)
                            .VIEW(true)
                            .EDIT(true)
                            .build();
                    itemItems.add(itemItem);
                }
            });
            SAPQuotationSubmissionVO.Item build = SAPQuotationSubmissionVO.Item.builder().ITEM(itemItems).build();
            sapQuotationSubmissionVO.getITEM().add(build);
        });
        String url = dictClient.getValue(DictCodeConstant.THIRD_INTERFACE, DictCodeConstant.INQUIRY_QUOTATION, DEFAULT_TENANT_ID).getData();
        if (Strings.isBlank(url)) {
            CommonException.throwCommonException("未维护三方接口");
        }
        //不忽略空值
        ValueFilter valueFilter = (o, s, o1) -> o1 == null ? "" : o1;
        String body = JSON.toJSONString(sapQuotationSubmissionVO, valueFilter);
        body = JSONUtil.toJsonPrettyStr(JsonUtil.parse(body, Object.class));
        String response = HttpUtils.sapTask(url, Method.POST, new LinkedHashMap<>(), null, null, body, url);
        log.info(response);
        Map map = JSONUtil.toBean(response, Map.class);
        if (map.get("id") != null && map.get("id").equals("failed")) {
            CommonException.throwCommonException("sap返回数据异常");
        } else if (map.get("id") == null) {
            CommonException.throwCommonException("sap接口异常");
        }
        tmInquirySheet.setQuoteStatus(InquiryStatusEnum.FINISH.value());
        iInquirySheetService.updateById(tmInquirySheet);
    }
}
